package com.chexiehui.jc.ui.fragment;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.view.View;
import android.widget.TextView;

import com.aries.ui.view.radius.RadiusTextView;
import com.blankj.utilcode.util.SpanUtils;
import com.blankj.utilcode.util.StringUtils;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpFragment;
import com.chexiehui.jc.base.BasePage;
import com.chexiehui.jc.entity.PostInfo;
import com.chexiehui.jc.event.GlobalFollowUserEvent;
import com.chexiehui.jc.event.GlobalLikePostEvent;
import com.chexiehui.jc.event.GlobalPostAppraiseEvent;
import com.chexiehui.jc.mvp.mine.BrowseHistoryPostsCovenant;
import com.chexiehui.jc.mvp.mine.BrowseHistoryPostsPresenter;
import com.chexiehui.jc.ui.activity.ForumDynamicDetailsActivity;
import com.chexiehui.jc.ui.activity.ForumTribuneDetailsActivity;
import com.chexiehui.jc.utils.AppCommonUtil;
import com.chexiehui.jc.utils.BundleBuilder;
import com.chexiehui.jc.utils.GlideUtil;
import com.chexiehui.jc.utils.NoDoubleClickListener;
import com.chexiehui.jc.utils.NoDoubleClickUtils;
import com.chexiehui.jc.widget.LoadingLayout;
import com.chexiehui.jc.widget.NineGridTestLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Author: SongJun.
 * CreateDate: 2019/1/21 0021.
 * Description: 帖子浏览历史
 */

public class BrowseHistoryPostsFragment extends BaseMvpFragment<BrowseHistoryPostsPresenter>
        implements BrowseHistoryPostsCovenant.View, IBrowseHistory {
    public static BrowseHistoryPostsFragment getInstance() {
        BrowseHistoryPostsFragment fragment = new BrowseHistoryPostsFragment();
        return fragment;
    }

    @BindView(R.id.loadingLayout)
    LoadingLayout loadingLayout;
    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private CommonAdapter<PostInfo> listAdapter;
    private List<PostInfo> listData;
    private BasePage<PostInfo> page;

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_browse_history_posts;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        loadingLayout.setStatus(LoadingLayout.Loading);
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setDisableContentWhenLoading(true);
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.setEnableFooterFollowWhenLoadFinished(false);
        refreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        refreshLayout.setEnableScrollContentWhenRefreshed(true);
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mvpPresenter.getList(1);
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (page != null && page.getTotalRecordCount() > listAdapter.getDatas().size()) {
                    mvpPresenter.getList(page.getPageIndex() + 1);
                } else {
                    refreshLayout.finishLoadMoreWithNoMoreData();
                }
            }
        });

        loadingLayout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadingLayout.setStatus(LoadingLayout.Loading);
                mvpPresenter.getList(1);
            }
        });
        recycler.setLayoutManager(new LinearLayoutManager(mActivity));
        ((SimpleItemAnimator)recycler.getItemAnimator()).setSupportsChangeAnimations(false);
        recycler.getItemAnimator().setChangeDuration(0);
        listData = new ArrayList<>();
        listAdapter = new CommonAdapter<PostInfo>(mActivity, R.layout.item_forum_post, listData) {
            @Override
            protected void convert(ViewHolder holder, PostInfo item, int position) {
                holder.getView(R.id.tv_item_forum_name).setOnClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View view) {
                        startActivity(ForumTribuneDetailsActivity.class, new BundleBuilder()
                                .putString("forumId", item.getForumsId())
                                .create());
                    }
                });
                GlideUtil.loadImageViewCrop(mActivity, item.getAuthorPhoto(), holder.getView(R.id.iv_item_avatar), R.drawable.shape_circle, R.drawable.shape_circle);
                holder.setText(R.id.tv_item_forum_name, item.getForumsName());
                holder.setText(R.id.tv_item_name, item.getAuthorName());
                holder.setText(R.id.tv_item_brief, item.getAuthorRemark());
                TextView tv_item_content = holder.getView(R.id.tv_item_content);
                if (StringUtils.isTrimEmpty(item.getLabel())) {
                    tv_item_content.setText(item.getTitle());
                } else {
                    SpanUtils spanUtils = new SpanUtils();
                    if (item.getLabel().contains("置顶")) {
                        spanUtils.appendImage(R.mipmap.ic_post_zhiding, SpanUtils.ALIGN_BASELINE)
                                .appendSpace(15);
                    }
                    if (item.getLabel().contains("精华")) {
                        spanUtils.appendImage(R.mipmap.ic_post_jinghua, SpanUtils.ALIGN_BASELINE)
                                .appendSpace(15);
                    }
                    spanUtils.append(item.getTitle())
                            .setForegroundColor(ContextCompat.getColor(mActivity, R.color.c_333333))
                            .setBackgroundColor(ContextCompat.getColor(mActivity, R.color.colorWhite));
                    tv_item_content.setText(spanUtils.create());
                }
                holder.setText(R.id.tv_item_time, AppCommonUtil.friendlyTime(item.getCreateTime()));
                holder.setText(R.id.tv_item_appraise_count, item.getCommentNum() + "");
                TextView tv_item_follow_count = holder.getView(R.id.tv_item_follow_count);
                tv_item_follow_count.setText(item.getLikenum() + "");
                Drawable drawable1 = getResources().getDrawable(item.isLike() ? R.mipmap.ic_follow_36_s : R.mipmap.ic_follow_48);
                drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());
                tv_item_follow_count.setCompoundDrawables(drawable1, null, null, null);
                RadiusTextView rtv_item_follow_action = holder.getView(R.id.rtv_item_follow_action);
                rtv_item_follow_action.setVisibility(View.VISIBLE);
                rtv_item_follow_action.setSelected(item.isFollow());
                rtv_item_follow_action.setText(item.isFollow() ? "取消关注" : "关注");
                rtv_item_follow_action.setOnClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View view) {
                        mvpPresenter.doFollowPerson(item.getAuthorId());
                    }
                });
                tv_item_follow_count.setOnClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View view) {
                        mvpPresenter.doDianZan(item.getId());
                    }
                });
                NineGridTestLayout ngtv_item_image_box = holder.getView(R.id.ngtv_item_image_box);
                if (item.getPhotoList().size() > 0) {
                    ngtv_item_image_box.setVisibility(View.VISIBLE);
                    ngtv_item_image_box.setUrlList(item.getPhotoList());
                } else {
                    ngtv_item_image_box.setVisibility(View.GONE);
                }
            }
        };
        listAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if(NoDoubleClickUtils.isDoubleClick()) return;
                startActivity(ForumDynamicDetailsActivity.class, new BundleBuilder()
                        .putString("postId", listAdapter.getDatas().get(position).getId())
                        .create());
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        recycler.setAdapter(listAdapter);
        mvpPresenter.getList(1);
    }

    @Override
    protected BrowseHistoryPostsPresenter createPresenter() {
        return new BrowseHistoryPostsPresenter(this);
    }

    @Override
    public void onGetListSuccess(BaseModel<BasePage<PostInfo>> successResult) {
        page = successResult.getData();
        if (loadingLayout.getStatus() != LoadingLayout.Success) {
            loadingLayout.setStatus(LoadingLayout.Success);
        }
        if (refreshLayout.getState() == RefreshState.Refreshing) {
            refreshLayout.finishRefresh();
            listAdapter.getDatas().clear();
            listAdapter.getDatas().addAll(page.getItems());
            listAdapter.notifyDataSetChanged();
        } else if (refreshLayout.getState() == RefreshState.Loading) {
            listAdapter.getDatas().addAll(page.getItems());
            listAdapter.notifyDataSetChanged();
            if (page.getTotalRecordCount() <= listAdapter.getDatas().size()) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                refreshLayout.finishLoadMore(true);
            }
        } else {
            refreshLayout.finishRefresh();
            listAdapter.getDatas().clear();
            listAdapter.getDatas().addAll(page.getItems());
            listAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onGetListFailure(BaseModel<Object> failureResult) {
        if (Constants.PAGE_DATA_EMPTY == failureResult.getResultCode()) {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(true);
                if (listAdapter.getDatas().size() > 0) {
                    listAdapter.getDatas().clear();
                    listAdapter.notifyDataSetChanged();
                }
                loadingLayout.setStatus(LoadingLayout.Empty);
                loadingLayout.setEmptyText(failureResult.getResultInfo());
            } else if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                loadingLayout.setStatus(LoadingLayout.Empty);
                loadingLayout.setEmptyText(failureResult.getResultInfo());
            }
        } else {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(false);
            }
            if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMore(false);
            }
            if (listAdapter.getDatas().size() <= 0) {
                loadingLayout.setStatus(LoadingLayout.Error);
                loadingLayout.setErrorText(failureResult.getResultInfo());
            } else {
                showToast(failureResult.getResultInfo());
            }
        }
    }


    @Override
    public void onDoDianZanSuccess(BaseModel<String> successResult) {
        for (int i = 0; i < listAdapter.getDatas().size(); i++) {
            String id = listAdapter.getDatas().get(i).getId();
            if(id.equals(successResult.getData())){
                EventBus.getDefault().post(new GlobalLikePostEvent(successResult.getData(), !listAdapter.getDatas().get(i).isLike()));
                break;
            }
        }
    }

    @Override
    public void onDoDianZanFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public void onDoFollowPersonSuccess(BaseModel<String> successResult) {
        for (int i = 0; i < listAdapter.getDatas().size(); i++) {
            String id = listAdapter.getDatas().get(i).getAuthorId();
            if(id.equals(successResult.getData())){
                EventBus.getDefault().post(new GlobalFollowUserEvent(successResult.getData(), !listAdapter.getDatas().get(i).isFollow()));
                break;
            }
        }
    }

    @Override
    public void onDoFollowPersonFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Subscribe
    public void onGlobalLikePostEvent(GlobalLikePostEvent event){
        if(event != null && !StringUtils.isTrimEmpty(event.getPostId())){
            for (int i = 0; i < listAdapter.getDatas().size(); i++) {
                String id = listAdapter.getDatas().get(i).getId();
                if(id.equals(event.getPostId())){
                    listAdapter.getDatas().get(i).setLike(event.isLiked());
                    listAdapter.getDatas().get(i).setLikenum(listAdapter.getDatas().get(i).getLikenum() + (event.isLiked() ? 1 : -1));
                    listAdapter.notifyItemChanged(i);
                    break;
                }
            }
        }
    }
    @Subscribe
    public void onGlobalPostAppraiseEvent(GlobalPostAppraiseEvent event){
        if(event != null && !StringUtils.isTrimEmpty(event.getPostId())){
            for (int i = 0; i < listAdapter.getDatas().size(); i++) {
                String id = listAdapter.getDatas().get(i).getId();
                if(id.equals(event.getPostId())){
                    listAdapter.getDatas().get(i).setCommentNum(event.getNum());
                    listAdapter.notifyItemChanged(i);
                    break;
                }
            }
        }
    }

    @Subscribe
    public void onGlobalFollowUserEvent(GlobalFollowUserEvent event){
        if(event != null && !StringUtils.isTrimEmpty(event.getUserId())){
            for (int i = 0; i < listAdapter.getDatas().size(); i++) {
                String id = listAdapter.getDatas().get(i).getAuthorId();
                if(id.equals(event.getUserId())){
                    listAdapter.getDatas().get(i).setFollow(event.isFollow());
                    listAdapter.notifyItemChanged(i);
                }
            }
        }
    }

    @Override
    public int getDataSize() {
        return listData == null ? 0 : listData.size();
    }

    @Override
    public void onClearRefresh() {
        try {
            loadingLayout.setStatus(LoadingLayout.Loading);
            mvpPresenter.getList(1);
        }catch (Exception e){}

    }
}
